package com.taobao.fanli.service;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.NTbkItem;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.request.WirelessShareTpwdQueryRequest;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.taobao.api.response.WirelessShareTpwdQueryResponse;
import com.taobao.fanli.config.TaobaoConfig;
import com.taobao.fanli.dao.mapper.TaobaoMapper;
import com.taobao.fanli.dao.model.Taobao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * @author:xiaolei
 * @date:2018/4/10
 */
@Service
public class TaobaoApiService {
    private static final Logger logger = LoggerFactory.getLogger("TaobaoApiService");

    @Resource
    private TaobaoConfig taobaoConfig;
    @Resource
    private TaobaoMapper taobaoMapper;

    @Async
    public void dealData(Integer id, String content) {
        String url = taobaoConfig.getUrl();
        String appkey = taobaoConfig.getAppkey();
        String secret = taobaoConfig.getSecret();
        try{
            TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
            WirelessShareTpwdQueryRequest req = new WirelessShareTpwdQueryRequest();
            req.setPasswordContent(content);
            WirelessShareTpwdQueryResponse response = client.execute(req);
            updateTaobao(id, response);
        }catch (ApiException e){
            logger.error("调用淘宝接口报错：", e);
            Taobao taobao = taobaoMapper.getOne(id, null);
            if(taobao != null){
                taobao.setState((byte) 4);
                taobaoMapper.updateDynamic(taobao);
            }
        }
    }

    private void updateTaobao(Integer id, WirelessShareTpwdQueryResponse response){
        Taobao taobao = taobaoMapper.getOne(id, null);
        if(taobao != null && response.getSuc()){
            taobao.setTitle(response.getTitle());
            taobao.setThumbPicUrl(response.getThumbPicUrl());
            taobao.setPicUrl(response.getPicUrl());
            taobao.setNativeUrl(response.getNativeUrl());
            String url = response.getUrl();

            OkHttpClient okHttpClient = new OkHttpClient();
            Request build = new Request.Builder().url(url).build();
            try {
                Response execute = okHttpClient.newCall(build).execute();
                if(execute.priorResponse() != null) {
                    logger.info("xxxxxxxxx" + execute.priorResponse().code());
                    int code = execute.priorResponse().code();
                    if (code == 301 || code == 302) {
                        url = execute.priorResponse().header("location");
                    }
                }
            } catch (IOException e) {
                logger.error("请求商品地址失败 IOException:",e);
            } catch (Exception e){
                logger.error("请求商品地址失败 Exception:",e);
            }

            String taobaoUrlGoodsId = getTaobaoUrlGoodsId(url);
            Map<String, String> goodsInfo = getGoodsInfo(taobaoUrlGoodsId);
            if(goodsInfo != null){
                taobao.setTitle(goodsInfo.get("goodsTitle"));
            }
            taobao.setGoodsLink(url);
            if(response.getPrice() != null){
                taobao.setPrice(new Double(new Double(response.getPrice())* 100).intValue());
            }
            if(StringUtils.isEmpty(url)){
                taobao.setState((byte) 4);
            }else{
                taobao.setState((byte) 1);
            }

            taobao.setUpdateAt(new Date());
            taobaoMapper.updateDynamic(taobao);
        }else{
            if(taobao != null){
                taobao.setState((byte) 4);
                taobaoMapper.updateDynamic(taobao);
            }
        }
    }


    public Map<String, String> getGoodsInfo(String goodsId){
        String url = taobaoConfig.getUrl();
        String appkey = taobaoConfig.getAppkey();
        String secret = taobaoConfig.getSecret();
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setFields("num_iid");
        req.setNumIids(goodsId);
        TbkItemInfoGetResponse rsp = null;
        try {
            rsp = client.execute(req);
        } catch (Exception e) {
            logger.error("请求淘宝商品详情地址失败:",e);
            return null;
        }
        if(rsp.isSuccess()){
            List<NTbkItem> results = rsp.getResults();
            if(!results.isEmpty()){
                Map<String, String> map = new HashMap<>();
                for(NTbkItem nTbkItem : results){
                    String pictUrl = nTbkItem.getPictUrl();
                    String itemUrl = nTbkItem.getItemUrl();
                    String title = nTbkItem.getTitle();
                    map.put("goodsUrl", itemUrl);
                    map.put("goodsPic", pictUrl);
                    map.put("goodsTitle", title);
                }
                return map;
            }
             return null;
        }
        return null;
    }

    private String getTaobaoUrlGoodsId(String url){
        String[] params = url.split("[?]");
        if(params.length > 1){
            String[] split = params[1].split("[&]");
            for (String str : split){
                String[] param = str.split("[=]");
                if(param[0].equals("id")){
                    return param[1];
                }
            }
        }
        return null;
    }


}
